function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}
function setupResourceFilters(courseCode) {
    const chapterFilter = document.getElementById('chapterFilter');
    const fileTypeFilter = document.getElementById('fileTypeFilter');
    
    if (!chapterFilter || !fileTypeFilter) {
        console.error('筛选器元素未找到');
        return;
    }

    // 存储当前课程代码
    chapterFilter.dataset.courseCode = courseCode;
    fileTypeFilter.dataset.courseCode = courseCode;
    
    // 移除旧事件监听器
    const newChapterFilter = chapterFilter.cloneNode(true);
    const newFileTypeFilter = fileTypeFilter.cloneNode(true);
    
    chapterFilter.replaceWith(newChapterFilter);
    fileTypeFilter.replaceWith(newFileTypeFilter);
    
    // 添加新监听器
    const handleFilter = () => {
        const currentCode = newChapterFilter.dataset.courseCode || 
                          newFileTypeFilter.dataset.courseCode;
        if (currentCode) {
            filterResources(currentCode).catch(console.error);
        }
    };
    
    newChapterFilter.addEventListener('change', handleFilter);
    newFileTypeFilter.addEventListener('change', handleFilter);
}
// 在 resource.js 中添加
async function generateUniqueResourceId() {
    let resourceId;
    let isUnique = false;
    while (!isUnique) {
        resourceId = generateRandomString(50);
        const checkResponse = await fetch(`/check-resource-code?resourceId=${escapeHTML(resourceId)}`);
        const checkData = await checkResponse.json();
        if (!checkData.exists) {
            isUnique = true;
        }
    }
    return resourceId;
}
async function checkTutorPermission(tutorId, courseCode) {
    const response = await fetch(`/check-tutor-permission?tutor_id=${escapeHTML(tutorId)}&course_code=${escapeHTML(courseCode)}`);
    const data = await response.json();
    return data.hasPermission;
}
// 打开上传资源模态框
async function openUploadResourceModal(courseCode, teacherUserId) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const response = await fetch(`/user-info?username=${escapeHTML(username)}`);
    const data = await response.json();
    if (data.role === '教师'||data.role === '助教') {
        if (data.user_id == teacherUserId || (data.role === '助教' && await checkTutorPermission(data.user_id, courseCode))) {
            const chaptersResponse = await fetch(`/get-chapters?courseCode=${escapeHTML(courseCode)}`);
            const chapters = await chaptersResponse.json();
            if (chapters.length === 0) {
                alert('该课程目前没有章节，无法上传资源');
                return;
            }
            document.getElementById('uploadCourseCode').value = courseCode;
            // 获取该课程的已有资源，且 attachment 为 0
            const resourcesResponse = await fetch(`/get-resources/${escapeHTML(courseCode)}`);
            const resources = await resourcesResponse.json();
            const filteredResources = resources.filter(resource => Number(resource.attachment) === 0);
            const attachmentSelect = document.getElementById('attachment');
            attachmentSelect.innerHTML = '<option value="0">不依附任何资源</option>';
            filteredResources.forEach(resource => {
                const option = document.createElement('option');
                option.value = resource.resource_id;
                option.textContent = resource.resource_content.split('\\').pop();
                attachmentSelect.appendChild(option);
            });
            // 获取该课程的章节信息
            
            const belongChapterSelect = document.getElementById('belongChapter');
            belongChapterSelect.innerHTML = ''; // 清空原有的选项
            chapters.forEach(chapter => {
                const option = document.createElement('option');
                option.value = chapter.chapter_id;
                option.textContent = `第${escapeHTML(chapter.chapter_order + 1)}章 ${escapeHTML(chapter.chapter_title)}`;
                belongChapterSelect.appendChild(option);
            });
            document.getElementById('uploadResourceModal').style.display = 'block';
        } else {
            alert('你无法对不属于你的课程进行该操作');
        }
    } 
}

function openViewResourcesModal() {
    const modal = document.getElementById('viewResourcesModal');
    if (modal) {
        modal.style.display = 'block';
    } else {
        console.error('viewResourcesModal element not found');
    }
}

// 关闭上传资源模态框
function closeUploadResourceModal() {
    document.getElementById('uploadResourceModal').style.display = 'none';
}

// 上传资源
async function uploadResource() {
    const courseCode = document.getElementById('uploadCourseCode').value;
    const resourceFile = document.getElementById('resourceFile').files[0];
    const permission = document.getElementById('permission').value;
    const attachment = document.getElementById('attachment').value;
    const belongChapter = document.getElementById('belongChapter').value;

    if (!resourceFile) {
        alert('请选择要上传的文件');
        return;
    }
    if (!permission) {
        alert('查看权限不能为空');
        return;
    }

    if (Number(attachment)!== 0) {
        
        const attachmentInfo = await getResourceInfo(attachment);
        
        const fileExtension = resourceFile.name.split('.').pop().toLowerCase();
        const attachmentExtension = attachmentInfo.resource_content.split('.').pop().toLowerCase();

        if (fileExtension!== attachmentExtension) {
            alert('被依赖的资源与依赖资源的文件类型需要保持一致');
            return;
        }

        // 确保章节信息的数据类型一致
        const attachmentChapter = String(attachmentInfo.belong_chapter);

        if (attachmentChapter!== belongChapter) {
            alert('被依赖的资源与依赖资源的所属章节需要相同');
            //console.log('章节不匹配，阻止上传');
            return;
        }
    }

    // 检查班级权限
    if (permission!== 'all') {
        const classCodes = permission.split(',').map(code => code.trim());
        for (const classCode of classCodes) {
            const checkClassResponse = await fetch(`/check-class-code?classCode=${escapeHTML(classCode)}`);
            const checkClassData = await checkClassResponse.json();
            if (!checkClassData.exists) {
                alert('不合法的班级权限，因为有班级不存在');
                return;
            }
        }
    }

    // 生成唯一的 resource_id
    const resourceId = await generateUniqueResourceId();

    if (!belongChapter) {
        alert('请选择所属章节');
        return;
    }

    const formData = new FormData();
    formData.append('courseCode', courseCode);
    formData.append('resourceFile', resourceFile);
    formData.append('permission', permission);
    formData.append('attachment', attachment);
    formData.append('belongChapter', belongChapter);
    formData.append('resourceId', resourceId);
    
    const response = await fetch('/upload-resource', {
        method: 'POST',
        body: formData
    });

    // 检查响应状态
    if (!response.ok) {
        const errorData = await response.text();
        console.error('上传资源失败:', errorData);
        alert('上传资源失败，请稍后重试');
        return;
    }

    const result = await response.json();
    //console.log('上传成功:', result);
    alert(result.message);
    closeUploadResourceModal();
}

// 查看资源
// 标记是否已经检查过章节
let hasCheckedChapters = false;

async function viewResources(courseCode) {
    //console.log('viewResources called with courseCode:', courseCode);
    
    // 检查 courseCode 是否为空
    if (!courseCode) {
        console.error('课程编号为空');
        alert('课程编号不能为空');
        return;
    }
    
    try {
        // 首次加载时检查课程的章节信息
        if (!hasCheckedChapters) {
            const chaptersResponse = await fetch(`/get-chapters?courseCode=${escapeHTML(courseCode)}`);
            const chapters = await chaptersResponse.json();

            // 检查是否有章节
            if (chapters.length === 0) {
                //console.log('该课程没有章节');
                alert('该课程目前没有章节，无法查看资源');
                return;
            }

            // 填充章节选择框
            const chapterFilter = document.getElementById('chapterFilter');
            if (!chapterFilter) {
                console.error('chapterFilter元素未找到');
                return;
            }
            chapterFilter.innerHTML = '<option value="all">全部章节</option>';
            chapters.forEach(chapter => {
                const option = document.createElement('option');
                option.value = chapter.chapter_id;
                option.textContent = `第${escapeHTML(chapter.chapter_order + 1)}章 ${escapeHTML(chapter.chapter_title)}`;
                chapterFilter.appendChild(option);
            });

            //hasCheckedChapters = true;
        }

        // 确保courseCode是字符串
        if (typeof courseCode !== 'string') {
            console.error('无效的courseCode:', courseCode);
            return;
        }
        
        // 设置筛选器的事件监听器（使用闭包捕获courseCode）
        setupResourceFilters(courseCode);
        //console.log('设置筛选器的事件监听器',courseCode);
        // 初始加载时应用筛选（默认显示所有资源）
        try {
            await filterResources(courseCode)
                .then(() => {
                    // 添加点击事件阻止
                    document.querySelectorAll('#chapterFilter, #fileTypeFilter').forEach(el => {
                        el.addEventListener('click', e => e.stopPropagation());
                    });
                    
                    // 检查模态框元素是否存在
                    const modal = document.getElementById('viewResourcesModal');
                    if (!modal) {
                        console.error('viewResourcesModal元素未找到');
                        return;
                    }
                    
                    // 打开资源查看模态框
                    //openViewResourcesModal();
                })
                .catch(err => {
                    console.error('filterResources failed:', err);
                });
        } catch (error) {
            console.error('Error in filterResources await:', error);
        }
        
        // 移除setTimeout检查
    } catch (error) {
        console.error('获取资源失败:', error);
        alert('获取资源失败，请稍后重试');
    }
}

function closeViewResourcesModal() {
    closeModal('viewResourcesModal');
    hasCheckedChapters = false;
}

async function downloadResource(resourceId) {
    try {
        // 获取资源对应的课程代码
        const response = await fetch(`/get-resource-course-code/${escapeHTML(resourceId)}`);
        const { courseCode } = await response.json();

        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
        const userData = await userResponse.json();
        if (userData.role === '助教'&&await checkTutorPermission(userData.user_id, courseCode)){
            // 权限检查通过，进行下载
            window.location.href = `/download-resource/${escapeHTML(resourceId)}`;
            return;
        }
        // 检查用户是否为教师
        if (userData.role === '教师') {
            // 获取教师创建的课程
            const teacherCoursesResponse = await fetch('/get-my-courses', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username })
            });
            const teacherCourses = await teacherCoursesResponse.json();
            const isCourseBelongToTeacher = teacherCourses.some(course => course.course_code === courseCode);
            if (!isCourseBelongToTeacher) {
                alert('你无法下载不属于你的课程的资源');
                return;
            }
            // 权限检查通过，进行下载
            window.location.href = `/download-resource/${escapeHTML(resourceId)}`;
            return;
        }

        // 检查该学生是否已选择该课程
        const selectedCoursesResponse = await fetch(`/get-selected-courses?username=${escapeHTML(username)}`);
        const selectedCourses = await selectedCoursesResponse.json();
        const isCourseSelected = selectedCourses.some(course => course.course_code === courseCode);
        if (!isCourseSelected) {
            alert('你未选择该课程，无法下载该课程的资源');
            return;
        }

        // 检查班级权限
        const { permission } = await getResourceInfo(resourceId);
        const userClass = await getUserClass(username);
        if (!checkPermission(permission, userClass)) {
            alert('由于教师设置的班级权限，你无法下载该资源');
            return;
        }
        if(userData.role != '教师'){
            await markResourceAsLearned(resourceId, userData.user_id);
        }
        // 权限检查通过，进行下载
        window.location.href = `/download-resource/${escapeHTML(resourceId)}`;
    } catch (error) {
        console.error('Error downloading resource:', error);
        alert('下载资源失败，请稍后重试');
    }
}

async function openAllVersionsModal(resourceId) {
    //console.log('openAllVersionsModal called with resourceId:', resourceId);
    try {
        const response = await fetch(`/get-resource-versions/${escapeHTML(resourceId)}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${escapeHTML(response.status)}`);
        }
        const versions = await response.json();
        const versionList = document.getElementById('versionList');
        
        versionList.innerHTML = versions.length > 0 ? '' : '<p class="text-gray-500 text-center py-4">暂无历史版本</p>';

        versions.forEach((version, index) => {
            const fileExtension = version.resource_content.split('.').pop().toLowerCase();
            const isLatest = index === 0;
            
            const versionItem = document.createElement('div');
            versionItem.className = 'version-item bg-white rounded-lg shadow-sm p-4 mb-3 border border-gray-100 hover:shadow-md transition-all';
            
            versionItem.innerHTML = `
                <div class="version-header flex items-center justify-between mb-2">
                    <div class="flex items-center">
                        <i class="${getFileIconClass(fileExtension).join(' ')} text-xl mr-3 ${getFileColorClass(fileExtension)}"></i>
                        <div>
                            <h4 class="font-medium text-gray-800 truncate max-w-xs">
                                ${version.resource_content.split('\\').pop()}
                                ${isLatest ? '<span class="ml-2 bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">最新</span>' : ''}
                            </h4>
                            <p class="text-sm text-gray-500">
                                <i class="far fa-clock mr-1"></i>
                                创建时间: ${escapeHTML(new Date(version.create_time).toLocaleString())}
                            </p>
                        </div>
                    </div>
                    <span class="version-number bg-blue-100 text-blue-800 text-xs font-medium px-2 py-1 rounded-full">
                        v${escapeHTML(versions.length - index)}
                    </span>
                </div>
                
                <div class="version-actions flex justify-end space-x-2 mt-3">
                    <button onclick="previewResource('${escapeHTML(version.resource_id)}')" 
                            class="action-btn bg-blue-50 text-blue-600 hover:bg-blue-100 px-3 py-1 rounded">
                        <i class="fas fa-eye mr-1"></i>预览
                    </button>
                    <button onclick="downloadResource('${escapeHTML(version.resource_id)}')" 
                            class="action-btn bg-green-50 text-green-600 hover:bg-green-100 px-3 py-1 rounded">
                        <i class="fas fa-download mr-1"></i>下载
                    </button>
                </div>
            `;
            
            versionList.appendChild(versionItem);
        });

        // 统一模态框显示方式
        const modal = document.getElementById('allVersionsModal');
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
        modal.style.display = 'flex';

    } catch (error) {
        console.error('获取资源版本失败:', error);
        alert('获取资源版本失败，请稍后重试');
    }
}

function closeAllVersionsModal(){
    document.getElementById('allVersionsModal').style.display = 'none';
}

async function previewResource(resourceId) {
    const { courseCode, permission, resource_content } = await getResourceInfo(resourceId);
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${escapeHTML(username)}`);
    const userData = await userResponse.json();

    if (userData.role === '助教'&&await checkTutorPermission(userData.user_id, courseCode)){
        // 权限检查通过，进行预览
        const fileExtension = resource_content.split('.').pop().toLowerCase();
    if (['pdf', 'mp3'].includes(fileExtension)) {
        // 实现在线预览逻辑
        if(userData.role != '教师'){
            await markResourceAsLearned(resourceId, userData.user_id);
        }
        window.open(`/preview-resource/${escapeHTML(resourceId)}`, '_blank');
    } else {
        alert('该文件类型不支持在线预览');
        return;
    }
    }
    // 检查用户是否为教师
    if (userData.role === '教师') {
        // 获取教师创建的课程
        const teacherCoursesResponse = await fetch('/get-my-courses', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });
        const teacherCourses = await teacherCoursesResponse.json();
        const isCourseBelongToTeacher = teacherCourses.some(course => course.course_code === courseCode);
        if (!isCourseBelongToTeacher) {
            alert('你无法预览不属于你的课程的资源');
            return;
        }
        const fileExtension = resource_content.split('.').pop().toLowerCase();
        if (['pdf', 'mp3'].includes(fileExtension)) {
            // 实现在线预览逻辑
            if(userData.role != '教师'){
                await markResourceAsLearned(resourceId, userData.user_id);
            }
            window.open(`/preview-resource/${escapeHTML(resourceId)}`, '_blank');
        } else {
            alert('该文件类型不支持在线预览');
        }
        return;
    }
    // 检查该学生是否已选择该课程
    const selectedCoursesResponse = await fetch(`/get-selected-courses?username=${escapeHTML(username)}`);
    const selectedCourses = await selectedCoursesResponse.json();
    const isCourseSelected = selectedCourses.some(course => {
        return course.course_code === courseCode;
    });
    if (!isCourseSelected) {
        alert('你未选择该课程，无法预览该课程的资源');
        return;
    }
    const userClass = await getUserClass(username);

    if (!checkPermission(permission, userClass)) {
        alert('由于教师设置的班级权限，你无法进行该操作');
        return;
    }

    const fileExtension = resource_content.split('.').pop().toLowerCase();
    if (['pdf', 'mp3'].includes(fileExtension)) {
        // 实现在线预览逻辑
        if(userData.role != '教师'){
            await markResourceAsLearned(resourceId, userData.user_id);
        }
        window.open(`/preview-resource/${escapeHTML(resourceId)}`, '_blank');
    } else {
        alert('该文件类型不支持在线预览');
    }
}

async function getResourceInfo(resourceId) {
    const response = await fetch(`/get-resource-info/${escapeHTML(resourceId)}`);
    const data = await response.json();
    return {
        courseCode: data.course_code,
        permission: data.permission,
        resource_content: data.resource_content,
        belong_chapter: data.belong_chapter // 添加章节信息返回
    };
}

async function getUserClass(username) {
    if (username === undefined) {
        //console.log("username传递错误");
        return null;
    }
    try {
        const response = await fetch(`/get-user-class?username=${escapeHTML(username)}`);
        if (!response.ok) {
            console.log("响应失败");
            return null;
        }
        const data = await response.json();
        if (data.class_code === undefined) {
            console.log(data.message);
        }
        return data.class_code;
    } catch (error) {
        console.error('获取用户班级信息失败:', error);
        return null;
    }
}

function checkPermission(permission, userClass) {
    const trimmedPermission = permission.trim().toLowerCase();
    if (trimmedPermission === 'all') {
        return true;
    }
    const allowedClasses = trimmedPermission.split(',').map(classCode => classCode.trim().toLowerCase());
    const trimmedUserClass = userClass.trim().toLowerCase();
    const result = allowedClasses.includes(trimmedUserClass);
    //console.log('Allowed classes:', allowedClasses);
    //console.log('User class:', trimmedUserClass);
    //console.log('Check result:', result);
    return result;
}

// 为查看课程资源模态框添加返回按钮
/*function addBackButtonToViewResourcesModal() {
        const viewResourcesModal = document.getElementById('viewResourcesModal');
        if (!viewResourcesModal) {
            console.error('无法找到 viewResourcesModal 元素');
            return;
        }
        
        const backButton = document.createElement('button');
        backButton.textContent = '返回';
        backButton.addEventListener('click', closeViewResourcesModal);
        
        const modalContent = viewResourcesModal.querySelector('.modal-content');
        if (modalContent) {
            modalContent.appendChild(backButton);
        } else {
            console.error('无法找到 .modal-content 元素');
        }
    }*/

// 为查看该资源所有版本的模态框添加返回按钮
/*function addBackButtonToAllVersionsModal() {
    const allVersionsModal = document.getElementById('allVersionsModal');
    const backButton = document.createElement('button');
    backButton.textContent = '返回';
    backButton.addEventListener('click', closeAllVersionsModal);
    allVersionsModal.querySelector('.modal-content').appendChild(backButton);
}*/

// 在页面加载时添加返回按钮
window.addEventListener('load', () => {
    //addBackButtonToViewResourcesModal();
    //addBackButtonToAllVersionsModal();
});

// 在resource.js中添加以下代码
document.addEventListener('DOMContentLoaded', () => {
    // 从URL获取courseCode
    const urlParams = new URLSearchParams(window.location.search);
    const courseCode = urlParams.get('courseCode');
    
    if (courseCode && typeof courseCode === 'string') {
        // 使用setupResourceFilters设置正确的监听器
        setupResourceFilters(courseCode);
    } else {
        //console.error('无效的courseCode参数:', courseCode);
    }
});

// 添加防抖计时器
let filterDebounceTimer = null;

async function filterResources(courseCode) {
    //console.log('filterResources called with:', courseCode);
    
    // 严格的参数校验
    if (typeof courseCode !== 'string' || !courseCode.trim()) {
        console.error('无效的courseCode参数:', courseCode);
        return Promise.reject(new Error('无效的courseCode参数'));
    }
    
    if (filterDebounceTimer) {
        clearTimeout(filterDebounceTimer);
    }
    
    return new Promise((resolve, reject) => {
        filterDebounceTimer = setTimeout(async () => {
            try {
                // 确保每次执行后清除计时器
                filterDebounceTimer = null;
                
                // 验证参数
                if (typeof courseCode !== 'string' || !courseCode.trim()) {
                    console.error('无效的courseCode:', courseCode);
                    return;
                }

                const chapterFilter = document.getElementById('chapterFilter')?.value || 'all';
                const fileTypeFilter = document.getElementById('fileTypeFilter')?.value || 'all';

                try {
                    const resourcesResponse = await fetch(`/get-resources/${escapeHTML(courseCode)}`);
        if (!resourcesResponse.ok) {
            throw new Error(`HTTP error! status: ${escapeHTML(resourcesResponse.status)}`);
        }
        const resources = await resourcesResponse.json();

        let filteredResources = resources.filter(resource => Number(resource.attachment) === 0);

                    // 章节筛选 - 优化后的逻辑
                    if (chapterFilter !== 'all') {
                        filteredResources = filteredResources.filter(resource => {
                            const belongChapter = resource.belong_chapter;
                            // 处理null/undefined情况
                            if (belongChapter == null) {
                                return false; // 不显示未分配章节的资源
                            }
                            // 严格字符串比较
                            const match = String(belongChapter) === String(chapterFilter);
                            
                            return match;
                        });
                    }

                    // 文件类型筛选 - 扩展支持类型
                    if (fileTypeFilter !== 'all') {
                        const commonTypes = ['pptx', 'pdf', 'xlsx', 'mp3', 'docx', 'jpg', 'png', 'zip'];
                        filteredResources = filteredResources.filter(resource => {
                            const fileName = resource.resource_content.split('\\').pop();
                            const lastDotIndex = fileName.lastIndexOf('.');
                            const fileExtension = lastDotIndex === -1 ? '' : fileName.substring(lastDotIndex + 1).toLowerCase();

                            if (fileTypeFilter === 'other') {
                                return !commonTypes.includes(fileExtension);
                            }
                            return fileExtension === fileTypeFilter;
                        });
                    }

                    const resourceList = document.getElementById('resourceList');
                    resourceList.innerHTML = '';

                    if (filteredResources.length === 0) {
                        resourceList.innerHTML = '<p class="no-content-message">暂无符合条件的课程资源</p>';
                    } else {
                        // 在filterResources函数中修改资源卡片创建部分
                        filteredResources.forEach(resource => {
                            const listItem = document.createElement('div');
                            listItem.classList.add('resource-card');
                            
                            // 卡片头部
                            const cardHeader = document.createElement('div');
                            cardHeader.classList.add('resource-header');
                            
                            const fileIcon = document.createElement('i');
                            const fileExtension = resource.resource_content.split('.').pop().toLowerCase();
                            const iconClasses = getFileIconClass(fileExtension);
                            iconClasses.forEach(className => fileIcon.classList.add(className));
                            fileIcon.style.fontSize = '24px'; // 增大图标大小
                            cardHeader.appendChild(fileIcon);
                            
                            const resourceName = document.createElement('span');
                            resourceName.classList.add('resource-name');
                            resourceName.textContent = resource.resource_content.split('\\').pop();
                            resourceName.style.fontSize = '16px'; // 增大字体大小
                            cardHeader.appendChild(resourceName);
                            
                            // 卡片内容
                            const cardContent = document.createElement('div');
                            cardContent.classList.add('resource-content');
                            
                            const createTime = document.createElement('p');
                            createTime.classList.add('resource-meta');
                            
                            const timeIcon = document.createElement('i');
                            timeIcon.classList.add('far', 'fa-clock');
                            timeIcon.style.fontSize = '16px'; // 增大时钟图标
                            createTime.appendChild(timeIcon);
                            createTime.appendChild(document.createTextNode(` 创建时间: ${escapeHTML(resource.create_time)}`));
                            createTime.style.fontSize = '14px'; // 增大时间文字
                            cardContent.appendChild(createTime);
                            
                            // 卡片底部按钮
                            const cardFooter = document.createElement('div');
                            cardFooter.classList.add('resource-footer');
                            
                            const viewAllVersionsButton = document.createElement('button');
                            viewAllVersionsButton.classList.add('resource-btn', 'versions-btn');
                            
                            const historyIcon = document.createElement('i');
                            historyIcon.classList.add('fas', 'fa-history');
                            historyIcon.style.fontSize = '16px'; // 增大历史图标
                            viewAllVersionsButton.appendChild(historyIcon);
                            viewAllVersionsButton.appendChild(document.createTextNode(' 版本历史'));
                            viewAllVersionsButton.style.backgroundColor = '#4f46e5'; // 给按钮添加颜色
                            viewAllVersionsButton.style.color = 'white';
                            viewAllVersionsButton.addEventListener('click', () => openAllVersionsModal(resource.resource_id));
                            cardFooter.appendChild(viewAllVersionsButton);
                            
                            // 组装卡片
                            listItem.appendChild(cardHeader);
                            listItem.appendChild(cardContent);
                            listItem.appendChild(cardFooter);
                            
                            resourceList.appendChild(listItem);
                        });

                    }
                    //console.log('filterResources completed successfully');
                    resolve();
                } catch (error) {
                    console.error('获取资源数据时出错:', error);
                    alert('获取资源数据失败，请稍后重试');
                    reject(error);
                }
            } catch (error) {
                console.error('Error getting resources:', error);
                alert('获取资源失败，请稍后重试');
                reject(error);
            }
        }, 100);
    });
}

// 新增辅助函数：标记资源为已学习
async function markResourceAsLearned(resourceId, userId) {
    try {
        const response = await fetch('/learn-resource', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ resource_id: resourceId, user_id: userId })
        });
        
        const result = await response.json();
        //console.log('标记学习状态:', result);
    } catch (error) {
        console.error('Error marking resource as learned:', error);
        // 静默处理错误，不影响主要操作
    }
}

function new_openModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.add('active');
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
}

// 关闭模态框
function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('active');
    modal.style.display = 'none';
    modal.classList.remove('active');
    document.body.style.overflow = '';
}

async function new_openViewResourcesModal(courseCode){
    const chaptersResponse = await fetch(`/get-chapters?courseCode=${escapeHTML(courseCode)}`);
    const chapters = await chaptersResponse.json();

    // 检查是否有章节
    if (chapters.length === 0) {
        //console.log('该课程没有章节');
        alert('该课程目前没有章节，无法查看资源');
        return;
    }
    new_openModal('viewResourcesModal');
    viewResources(courseCode);
    //console.log('new_openViewResourcesModal called with:', courseCode);
}

// 辅助函数：根据文件类型返回对应的图标类
function getFileIconClass(extension) {
    const iconMap = {
        pdf: ['far', 'fa-file-pdf'],
        pptx: ['far', 'fa-file-powerpoint'],
        docx: ['far', 'fa-file-word'],
        xlsx: ['far', 'fa-file-excel'],
        mp3: ['far', 'fa-file-audio'],
        jpg: ['far', 'fa-file-image'],
        png: ['far', 'fa-file-image'],
        zip: ['far', 'fa-file-archive'],
        default: ['far', 'fa-file']
    };
    return iconMap[extension] || iconMap.default;
}

// 辅助函数 - 获取文件类型对应的颜色类
function getFileColorClass(extension) {
    const colorMap = {
        pdf: 'text-red-500',
        doc: 'text-blue-500',
        docx: 'text-blue-500',
        xls: 'text-green-500',
        xlsx: 'text-green-500',
        ppt: 'text-orange-500',
        pptx: 'text-orange-500',
        default: 'text-gray-500'
    };
    return colorMap[extension] || colorMap.default;
}

function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/[&<>"']/g, function (match) {
        switch (match) {
            case '&':
                return '&amp;';
            case '<':
                return '&lt;';
            case '>':
                return '&gt;';
            case '"':
                return '&quot;';
            case "'":
                return '&#039;';
        }
    });
}


export {
     generateRandomString,
         generateUniqueResourceId,
          escapeHTML,
           getFileIconClass,
          getFileColorClass,
          checkPermission,
          // 模态框与筛选
          setupResourceFilters,
          openUploadResourceModal,
          closeUploadResourceModal,
          openViewResourcesModal,
          closeViewResourcesModal,
          new_openViewResourcesModal,
          openAllVersionsModal,
          closeAllVersionsModal,
          new_openModal,
          closeModal,
          // 核心业务
        uploadResource,
        viewResources,
        downloadResource,
        previewResource,
        getResourceInfo,
        getUserClass,
        filterResources,
}